<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    protected $table='blog_category';
    protected $primaryKey='cate_id';
    public $timestamps=false;
    protected $guarded=[];

    public function tree()
    {
        $categorys = $this->all();
        return $this->getTree($categorys,'cate_name','cate_id','cate_pid');
    }

//    public static function tree()
//    {
//        $categorys = Category::all();
//        return (new Category)->getTree($categorys,'cate_name','cate_id','cate_pid');
//    }

    public function getTree($data,$field_name,$field_id='id',$field_pid='pid',$pid=0)
    {
        $arr = array();
        foreach ($data as $k=>$v){
            if($v->$field_pid==$pid){
                $data[$k]["_".$field_name] = $data[$k][$field_name];
                $arr[] = $data[$k];
                foreach ($data as $m=>$n){
                    if($n->$field_pid == $v->$field_id){
                        $data[$m]["_".$field_name] = '├─ '.$data[$m][$field_name];
                        $arr[] = $data[$m];
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 递归展示
     * @param $data
     * @param int $pid
     * @return array
     * create by wenQing
     */
    public function getTreeDG(&$data,$pid=0)
    {
        static $sub = [];
        $result = $data;

        //获取所需要的数据
        foreach($data as $k2 => $v2)
        {
            if($v2['cate_pid'] != $pid) unset($data[$k2]);
        }
        //循环数据，赋值操作
        foreach ($data as $k => $v)
        {
            if ($v['cate_pid'] == $pid)
            {
                $sub[] = $v;
                $this->getTreeDG($result, $v['cate_id']);
            }
        }

        return $sub;
    }
}
